package com.bj58.mis.apm.server.kylinreceive.schedule;

import com.bj58.mis.apm.server.kylinreceive.mapper.KylinLogTimesMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author: wangxw
 * @Date: 2018/7/20 15:04
 */
@Component
@ConditionalOnProperty(name = "schedule.query.times.enable", havingValue = "true")
public class QueryTimeSchedule {

    @Resource
    private KylinLogTimesMapper logTimesMapper;

    private String[] tableNames =
            {"kylin_query_times_cube",
            "kylin_query_times_group",
            "kylin_query_times_column",
            "kylin_query_times_cuboid"};

    /**
     * 定时任务 每天
     * 1.更新kylin_cube_query_times查询有效次数effective_times = effective_times * coef
     * 2.更新kylin_cube_query_group查询有效次数effective_times = effective_times * coef
     * 3.更新kylin_cube_query_column查询有效次数effective_times = effective_times * coef
     * 4.更新kylin_cube_query_column步长step_size和权重weight
     * 计算方法：
     * coef是每天衰减倍数
     * weight默认值100
     * step_size默认值0，最大值是3，最小值是-5
     * 1.如果距上次使用间隔0天，则步长加1
     * 2.如果距上次使用间隔1天，则步长不变
     * 3.如果距上次使用间隔2天及以上，则步长-1
     */
    @Scheduled(cron = "${schedule.query.times.cron}")
    public void dealQueryTimes(){
        for(String tableName : tableNames){
            logTimesMapper.updateQueryEffectiveTimes(tableName, getAttenuationCoefficientByDay(1));
        }
        //计算步长和权重
        logTimesMapper.updateWeightAndStep();
    }

    private Double getAttenuationCoefficientByDay(int days){
        return Math.pow(0.977D,days);
    }
}
